package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.SupplierContactDao;
import com.xbongbong.saas.domain.entity.ext.SupplierContactEntityExt;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierContactSubDataModel;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author WangJian
 * @date  2019-01-25 14:01
 **/
@Service("SupplierContactModel")
public class SupplierContactModelImpl implements SupplierContactModel{
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private SupplierContactDao supplierContactDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private SupplierContactSubDataModel supplierContactSubDataModel;
    @Resource
    private ShowFormatHelp showFormatHelp;

    @Override
    public Integer insert(SupplierContactEntityExt entity) throws XbbException {
        //TODO  先进行数据库的插入动作
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = supplierContactDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        return insert;
    }

    @Override
    public Integer update(SupplierContactEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);

        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = supplierContactDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = supplierContactDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List findEntitys(Map<String, Object> param) {
        List<SupplierContactEntityExt> entitys = supplierContactDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return supplierContactDao.getEntitysCount(param);
    }

    /**
     * 查询单个实体
     *
     */
    @Override
    public SupplierContactEntityExt getByKey(Long key, String corpid) {
        SupplierContactEntityExt entityExt = supplierContactDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        return entityExt;
    }

    @Override
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {
        Integer integer = supplierContactDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);

        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT_SUB);
        return supplierContactDao.deleteByKey(key,corpid);
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = supplierContactDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
        }
        if (!subList.isEmpty()) {
            supplierContactSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = supplierContactDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            supplierContactSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return supplierContactDao.findEntitys(param);
    }

    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        Integer fromCopy = BasicConstant.ZERO;
        if(formatExplainDTO.getFromCopy() != null){
            // true: 复制1 false：编辑0
            fromCopy = formatExplainDTO.getFromCopy() ? BasicConstant.ONE : BasicConstant.ZERO;
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, SupplierContactEnum.SUPPLIER_ID.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(fieldAttrEntity.getAttr(), SupplierContactEnum.PHONE.getAttr())){
                // 补救之前供应商之前的showtype默认为1的情况，最大限度的保留客户数据
                if(Objects.nonNull(fieldAttrEntity)){
                    SubFormPoJo supplierPhoneSubForm = fieldAttrEntity.getSubForm();
                    if(Objects.nonNull(supplierPhoneSubForm)){
                        List<? extends FieldAttrEntity> items = supplierPhoneSubForm.getItems();
                        if(!items.isEmpty()){
                            Iterator<? extends FieldAttrEntity> iterator = items.iterator();
                            while (iterator.hasNext()) {
                                FieldAttrEntity subField = iterator.next();
                                if(Objects.nonNull(subField.getShowType())){
                                    subField.setShowType(ShowTypeEnum.ALL.getCode());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 供应商联系人编辑格式化数据格式
     *
     * @param formDataUpdateGetDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 参数格式错误异常
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public void formatData(SaasAnalysisDataDTO formDataUpdateGetDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result,SupplierContactEnum.SUPPLIER_ID.getAttr(),SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), SupplierContactEnum.SUPPLIER_ID.getFieldType());
        showFormatHelp.formatBirthday4Show(result,SupplierContactEnum.BIRTHDAY.getAttr(),SupplierContactEnum.BIRTHDAY_FLAG.getAttr());
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = supplierContactDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT);
        paasEsModel.update(insertDTO);
        return success;
    }
}
